package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.SysStudentBenefit;
import com.ruoyi.system.domain.SysStudentBenefitExchange;
import com.ruoyi.system.domain.SysStudentRank;
import com.ruoyi.system.service.SysStudentBenefitService;
import com.ruoyi.system.service.SysStudentRankService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/studentBenefit")
public class SysStudentBenefitController extends BaseController {

    @Resource
    private SysStudentBenefitService benefitService;

    @Resource
    private SysStudentRankService rankService;

    /**
     * 获取可兑换权益列表
     */
    @GetMapping("/list")
    public AjaxResult getBenefitList() {
        List<SysStudentBenefit> benefitList = benefitService.getEnableBenefits();
        return AjaxResult.success(benefitList);
    }

    /**
     * 兑换权益（接收降级标识）
     */
    @PostMapping("/exchange/{benefitId}")
    public AjaxResult exchangeBenefit(
            @PathVariable Long benefitId,
            @RequestBody Map<String, Boolean> param
    ) {
        Long userId = getUserId();
        Boolean needDowngrade = param.getOrDefault("needDowngrade", false);
        benefitService.exchangeBenefit(userId, benefitId, needDowngrade);
        return AjaxResult.success("兑换成功，已完成经验扣减（如需降级已自动处理）");
    }

    /**
     * 获取兑换历史
     */
    @GetMapping("/exchange/history")
    public AjaxResult getExchangeHistory() {
        Long userId = getUserId();
        List<SysStudentBenefitExchange> historyList = benefitService.getUserExchangeHistory(userId);
        return AjaxResult.success(historyList);
    }

    /**
     * 获取当前用户经验值（适配文字段位）
     */
    @GetMapping("/currentExp")
    public AjaxResult getCurrentExp() {
        Long userId = getUserId();
        SysStudentRank userRank = rankService.selectRankByUserId(userId);
        Integer currentExp = userRank != null && userRank.getCurrentExp() != null
                ? userRank.getCurrentExp()
                : 0;
        return AjaxResult.success(currentExp);
    }

    /**
     * 获取当前用户段位（返回文字型段位，供前端显示）
     */
    @GetMapping("/currentRank")
    public AjaxResult getCurrentRank() {
        Long userId = getUserId();
        SysStudentRank userRank = rankService.selectRankByUserId(userId);
        if (userRank == null || userRank.getRankLevel() == null || userRank.getRankSubLevel() == null) {
            return AjaxResult.success("暂无段位");
        }
        // 返回“总段位+小段位”格式（如“秩序白银III”）
        String rankInfo = userRank.getRankLevel() + userRank.getRankSubLevel();
        return AjaxResult.success(rankInfo);
    }
}